package com.steven.im.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.orhanobut.logger.Logger;
import com.steven.im.App;
import com.steven.im.base.Constant;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.WXLoginEntry;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.BindMobileActivity;
import com.steven.im.ui.activity.LoginAndRegisterActivity;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.SaveParameterUtils;
import com.steven.im.utils.ToastUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import retrofit2.Response;

/**
 * 微信登录、分享相关
 */
public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，
        // 避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            App.getWXAPI().handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        App.getWXAPI().handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        Logger.i("onResp:" + baseResp.errCode);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (baseResp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH://登录(1)
                        //用户同意，得到code，获取access_token
                        String code = ((SendAuth.Resp) baseResp).code;
                        Log.i(TAG, "code:" + code);
                        getUserInfoByCode(code);
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX://分享(2)
                        ToastUtil.showShort(this, "分享成功");
                        finish();
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //取消或者拒绝，关闭当前页面
                finish();
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                break;
            default:
                break;
        }
    }

    /*
    通过code获取微信用户信息
     */
    private void getUserInfoByCode(String code) {
        Task.getApiService().wechatCode(code).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {

                    if ("0".equals(response.body().getCode())) {//成功
                        WXLoginEntry wxLoginEntry = GsonUtils.parseJSON(
                                response.body().getResult().toString(), WXLoginEntry.class);
                        if (wxLoginEntry != null) {
                            SPUtils.put(getApplicationContext(), Constant.WxInfo.WX_UNIONID, wxLoginEntry.getUnionId());
                            if (wxLoginEntry.isBinding()) {//需要绑定
                                startActivity(new Intent(WXEntryActivity.this, BindMobileActivity.class)
                                        .putExtra("unionId", wxLoginEntry.getUnionId()));
                                finish();
                            } else {//已经绑定手机号，登陆成功
                                SaveParameterUtils.saveJseSessionId(wxLoginEntry.getSessionId());
                                finish();
                                if (LoginAndRegisterActivity.mAct != null) {
                                    LoginAndRegisterActivity.mAct.finish();
                                }
                            }
                        } else {
                            ToastUtil.showShort(WXEntryActivity.this, "获取用户信息失败");
                            finish();
                        }
                    } else {//微信登录失败
                        ToastUtil.showShort(WXEntryActivity.this, response.body().getMessage());
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });

    }

}
